/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: peopleLog.c
> Author:kings
> Mail:kings 
> Created Time: 2024年12月04日 星期三 09时04分17秒
***************************************************/

#include "peopleLog.h"

int main(int argc,const char* argv[])
{
    USER* user = malloc(sizeof(USER)); // 分配内存
    if (user == NULL) {
        perror("分配内存失败!\n");
        return -1;
    }
    // 注册账户信息
    int result = register_user(user);

    //登录账户信息
    int win=userLog(user);

    // 释放内存
    free(user);
   // free(p);
    return 0;
}

// 打包JSON数据
char* packJson(USER* user)
 {
    char * p = (char*)malloc(1024); // 分配内存
    cJSON* root = cJSON_CreateObject(); // 创建JSON对象

    cJSON* post = cJSON_CreateString(user->post);// 创建JSON字符串
    cJSON* name = cJSON_CreateString(user->username); 
    cJSON* passwd = cJSON_CreateString(user->passwd);

    cJSON_AddItemToObject(root, "post", post);// 添加到JSON对象
    cJSON_AddItemToObject(root, "name", name); 
    cJSON_AddItemToObject(root, "pwd", passwd);

    strcpy(p, cJSON_Print(root)); // 将JSON对象转换为字符串

    cJSON_Delete(root); // 删除JSON对象
    free(post);
    free(name);
    free(passwd);
    return p;
}

//解析json数据包
int parseJson(const char* p) 
{
    cJSON* root = cJSON_Parse(p); // 解析JSON字符串

    cJSON* code = cJSON_GetObjectItem(root, "returncode"); // 获取JSON对象中的值

    int cd = cJSON_GetNumberValue(code); // 获取数值
    return cd;
}

//注册用户信息
int register_user(USER* user)
{
    //pthread_mutex_lock(&db_mutex);
    printf("请注册您的账户信息\n");
    printf("请输入您的职位\n");
    scanf("%s", user->post);
    printf( "请输入您的账户\n");
    scanf("%s",user->username);
    printf("请输入您的密码\n");
    scanf("%s",user->passwd);
    printf("您的账户是%s,密码为%s",user->username,user->passwd);
    char* p = packJson(user);
   // printf("p:%s", p);
    int ret = -1;
    if (send_msg(p) == 1)
    {
        ret = 0;//注册成功！
    }
    free(p);
    return ret;
}

//登录用户信息
int userLog(USER* user)
{
    char users[20] = { 0 };
    char word[20] = { 0 };
    printf("请输入您的账户名\n");
    scanf("%s", users);
    printf("请输入您的密码\n");
    scanf("%s", word);

    if (strcmp(users, user->username) == 0 || strcmp(word, user->passwd) == 0)
    {
        printf("登录成功\n");
        return 0;
    }
    else
    {
        printf("输入账户或者密码错误,请重新输入\n");
        return -1;
    }
}
//发送消息
int send_msg(const char* buf)
{
    int sc = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in caddr;
    caddr.sin_family = AF_INET;
    caddr.sin_port = htons(PROT);
    caddr.sin_addr.s_addr = inet_addr(IP);
    int isconnect = connect(sc, (struct sockaddr*)&caddr, sizeof(caddr));
    if (isconnect == -1)
    {
        perror("connect");
        return -1;
    }
    printf("连接成功\n");
    char rev_buf[1024] = { 0 };
    int ws = write(sc, buf, strlen(buf));
    printf("write size:%d\n", ws);

    read(sc, rev_buf, sizeof(rev_buf));
    //解包
    int ret = parseJson(rev_buf);
    return ret;
}
